#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "rngs.h"

#define DEBUG 0
#define NOISY_TEST 1

int CheckdiscardCard(int handPos, int currentPlayer, struct gameState *post, int trashFlag)
{
	  struct gameState pre;
  memcpy (&pre, post, sizeof(struct gameState));
  int r;
  r = discardCard (handPos, currentPlayer, post, trashFlag);
  //if card is not trashed, added to Played pile 
  if (trashFlag < 1)
    {
      //add card to played pile
      pre.playedCards[pre.playedCardCount] = pre.hand[currentPlayer][handPos]; 
      pre.playedCardCount++;
    }
	
  //set played card to -1
 pre.hand[currentPlayer][handPos] = -1;
	
  //remove card from player's hand
  if ( handPos == (pre.handCount[currentPlayer] - 1) ) 	//last card in hand array is played
    {
      //reduce number of cards in hand
      pre.handCount[currentPlayer]--;
    }
  else if ( pre.handCount[currentPlayer] == 1 ) //only one card in hand
    {
      //reduce number of cards in hand
      pre.handCount[currentPlayer]--;
    }
  else 	
    {
      //replace discarded card with last card in hand
      pre.hand[currentPlayer][handPos] = pre.hand[currentPlayer][ (pre.handCount[currentPlayer] - 1)];
      //set last card to -1
      pre.hand[currentPlayer][pre.handCount[currentPlayer] - 1] = -1;
      //reduce number of cards in hand
      pre.handCount[currentPlayer]--;
    }
	
  assert (r == 0);

  assert(memcmp(&pre, post, sizeof(struct gameState)) == 0);
  return 0;
}

int main () {{

  int i, n, r, p, handPos, trashFlag;

  struct gameState G;

  printf ("Testing DiscardCard.\n");

  printf ("RANDOM TESTS.\n");

  SelectStream(2);
  PutSeed(3);

  for (n = 0; n < 2000; n++) {
    for (i = 0; i < sizeof(struct gameState); i++) {
      ((char*)&G)[i] = floor(Random() * 256);
    }

		int numberOfPlayers = floor(Random() * MAX_PLAYERS);
		p = floor(Random() * numberOfPlayers);
		
		G.handCount[p] = floor(Random() * MAX_HAND);
		G.deckCount[p] = floor(Random() * MAX_DECK);
		G.discardCount[p] = floor(Random() * MAX_DECK);
		G.playedCardCount = floor(Random() * MAX_DECK);
		handPos = floor(Random() * G.handCount[p]);
		G.numActions = 0;
		G.whoseTurn = p;
		G.numPlayers = numberOfPlayers;
		trashFlag = floor(Random() * 2);
	
    CheckdiscardCard(handPos, p, &G,trashFlag);
  }

  printf ("ALL TESTS OK\n");

  exit(0);

  }

  return 0;
}
